﻿(function () {
    var _inited = false;
    var _handler = "../Handlers/UserInfoHandler.ashx";
    var _urhandler = "../Handlers/UserRightsHandler.ashx";

    var MenuCtrol = {
        getAllMenu: function () {
            $.ajax({
                type: "get",
                url: _urhandler + "?action=GetUserRights" + "&ts=" + new Date().valueOf(),
                dataType: 'json',
                async: false,
                success: function (data, textStatus) {
                    ProcessAjaxResult(data, textStatus,
                    function (data, textStatus) {
                        if (data != null && data.length > 0) {
                            $("table.MenuTable .MenuData").html("");
                            $(data).each(function () {
                                var rt = this;
                                var tr = "<tr RightFlag='" + rt.RightFlag + "'>";
                                tr += "<td class='checkCol'>";
                                tr += "<input type='checkbox' Rank='0' RightFlag='" + rt.RightFlag + "' />";
                                tr += "</td>";
                                tr += "<td class='checkCol'></td>";
                                tr += "<td class='tdName'>" + rt.FlagName + "</td>";
                                tr += "</tr>";
                                $("table.MenuTable .MenuData").append($(tr).data(rt));
                                if (rt.UserRights) {
                                    for (var i = 0; i < rt.UserRights.length; i++) {
                                        var st = rt.UserRights[i];
                                        var subtr = "<tr RightFlag='" + st.RightFlag + "'" + " RightID='" + st.RightID + "'>";
                                        subtr += "<td class='checkCol'></td>";
                                        subtr += "<td class='checkCol'>";
                                        subtr += "<input type='checkbox' Rank='1' RightFlag='" + st.RightFlag + "'" + " RightID='" + st.RightID + "' />";
                                        subtr += "</td>";
                                        subtr += "<td class='tdName'>" + st.RightName + "</td>";
                                        subtr += "</tr>";
                                        $("table.MenuTable .MenuData").append($(subtr).data(st));
                                    }
                                }
                            });
                            MenuCtrol.liveCheckboxEvent();
                            $("table.MenuTable").find("input[type='checkbox']").attr("disabled", "disabled");
                        }
                    },
                    function (err, textStatus) {
                        alert('操作失败');
                    },
                    this);
                }
            });
        },
        getMenuByUser: function (params) {
            $.ajax({
                type: "get",
                url: _urhandler + "?action=GetUserRightsByUserID&Params=" + encodeURIComponent($.toJSON(params.AutoID)) + "&ts=" + new Date().valueOf(),
                dataType: 'json',
                success: function (data, textStatus) {
                    ProcessAjaxResult(data, textStatus,
                    function (data, textStatus) {
                        $("table.MenuTable").find("input[type='checkbox']").removeAttr("checked");
                        if (data != null && data.length > 0) {
                            $(data).each(function () {
                                var rt = this;
                                if (rt.UserRights) {
                                    for (var i = 0; i < rt.UserRights.length; i++) {
                                        var st = rt.UserRights[i];
                                        if (st.SelectFlag > 0) {
                                            $("table.MenuTable .MenuData")
                                            .find("input[RightFlag='" + st.RightFlag + "'][RightID='" + st.RightID + "']")
                                            .attr("checked", "checked");
                                            $("table.MenuTable .MenuData")
                                            .find("input[Rank='0'][RightFlag='" + st.RightFlag + "']")
                                            .attr("checked", "checked");
                                        }
                                    }
                                }
                            });
                        }
                    },
                    function (err, textStatus) {
                        alert('操作失败');
                    },
                    this);
                }
            });
        },
        liveCheckboxEvent: function () {
            $("table.MenuTable .MenuData").find("input[type='checkbox']").bind("click", function () {
                if ($(this).attr("checked")) {
                    if ($(this).attr("RightID")) {
                        //叶子
                        $(this).attr("checked", "checked");
                        $("table.MenuTable .MenuData").find("input[Rank='0'][RightFlag='" + $(this).attr("RightFlag") + "']").attr("checked", "checked");
                    }
                    else {
                        //根
                        $("table.MenuTable .MenuData").find("input[RightFlag='" + $(this).attr("RightFlag") + "']").attr("checked", "checked");
                    }
                }
                else {
                    if ($(this).attr("RightID")) {
                        //叶子
                        $(this).removeAttr("checked");
                        if ($("input[Rank!='0'][RightFlag='" + $(this).attr("RightFlag") + "'][checked]").length == 0) {
                            $("table.MenuTable .MenuData").find("input[Rank='0'][RightFlag='" + $(this).attr("RightFlag") + "']").removeAttr("checked");
                        }
                    }
                    else {
                        //根
                        $("table.MenuTable .MenuData").find("input[RightFlag='" + $(this).attr("RightFlag") + "']").removeAttr("checked");
                    }
                }
            });
        }
    };

    function _init() {
        MenuCtrol.getAllMenu();
        _initUI();
        _initDetailUI();
        _getDataGroups();
    }

    function _handlerMsg(msg) {
        switch (msg) {
            case 0:
                alert('操作成功');
                break;
            case 100:
                alert('用户名相同');
                break;
            case 200:
                alert('旧口令不正确');
                break;
            default:
                alert('操作失败');
                break;
        }
    }

    function _initUI() {
        $('#btnSave', '.form-bar-rights').die().live('click', function () {
            var uwg = $("#currentUser", "table.MenuTable").data('data');
            if (uwg && uwg != null) {
                var params = {};
                var rights = [];
                $("input[Rank!='0'][checked]").each(function () {
                    var ur = $(this).closest('tr').data();
                    ur.SelectFlag = 1;
                    rights.push(ur);
                });
                params.UserInfoWithGroup = uwg;
                params.UserRights = rights;
                _saveData(params);
            }
            else {
                alert('请选择用户');
            }
        });
        $('span.file').die().live('click', function () {
            var li = $(this).closest('li');
            _initDetailUI(li.data('data'));
        });
    }

    function _initDetailUI(params) {
        if (params) {
            $("#currentUser", "table.MenuTable").data('data', params).html(params.UserName);
            //if (params.UserName != 'admin') {
                $("table.MenuTable").find("input[type='checkbox']").removeAttr("disabled");
                $('#btnSave', '.form-bar-rights').removeAttr('disabled');
//            }
//            else {
//                $("table.MenuTable").find("input[type='checkbox']").attr("disabled", "disabled");
//                $('#btnSave', '.form-bar-rights').attr('disabled', 'disabled');
//            }
            MenuCtrol.getMenuByUser(params);
        }
        else {
            $("#currentUser", "table.MenuTable").data('data', null).html('');
            $("table.MenuTable").find("input[type='checkbox']").removeAttr("checked");
            $("table.MenuTable").find("input[type='checkbox']").attr("disabled", "disabled");
            $('#btnSave', '.form-bar-rights').attr('disabled', 'disabled');
        }
    }

    function _getDataGroups() {
        $.ajax({
            type: "get",
            url: _handler + "?action=GetUserGroup" + "&ts=" + new Date().valueOf(),
            dataType: 'json',
            async: false,
            success: function (data, textStatus) {
                ProcessAjaxResult(data, textStatus,
                    function (data, textStatus) {
                        $("#usertree").empty();
                        if (data) {
                            for (var i = 0; i < data.length; i++) {
                                var d = data[i];
                                var li = "<li class='closed' style='white-space: nowrap;'>";
                                li += "<span class='folder'>";
                                li += "<label id='Label" + d.AutoID + "' code='" + d.AutoID + "'>";
                                li += d.GroupName;
                                li += "</label>";
                                li += "</span>";
                                li += "<ul code='" + d.AutoID + "'></ul>";
                                li += "</li>";
                                $(li).data('data', d).appendTo($('#usertree'));
                            }
                        }
                        _initTree();
                    },
                    function (err, textStatus) {
                        alert('操作失败');
                    },
                    this);
            }
        });
    }

    function _initTree() {
        $('#usertree').treeview({
            collapsed: false,
            animated: "medium",
            persist: "location",
            toggle: function () {
                var currentobj = $(this);
                if (!currentobj.is(":hidden")) {
                    var ul = currentobj;
                    _getDataUsers(ul);
                }
            },
            nodeclick: function () {
                _initDetailUI();
            }
        });
    }

    function _getDataUsers(ul) {
        var code = ul.attr("code");
        $.ajax({
            type: "get",
            url: _handler + "?action=GetUserInfo&Params=" + code + "&ts=" + new Date().valueOf(),
            dataType: 'json',
            async: false,
            success: function (data, textStatus) {
                ProcessAjaxResult(data, textStatus,
                    function (data, textStatus) {
                        ul.empty();
                        if (data) {
                            for (var i = 0; i < data.length; i++) {
                                var d = data[i];
                                var li = "<li class='closed' style='white-space: nowrap;'>";
                                li += "<span class='file'>";
                                li += "<label id='Label" + d.AutoID + "' code='" + d.AutoID + "'>";
                                li += d.UserName;
                                li += "</label>";
                                li += "</span>";
                                li += "</li>";
                                $(li).data('data', d).appendTo(ul);
                            }
                        }
                        $("#usertree").treeview({
                            add: branches
                        });
                    },
                    function (err, textStatus) {
                        alert('操作失败');
                    },
                    this);
            }
        });
    }

    function _saveData(params) {
        $.ajax({
            type: "post",
            url: _urhandler,
            data: "action=SaveUserRights&Params=" + encodeURIComponent($.toJSON(params)),
            dataType: 'json',
            success: function (data, textStatus) {
                ProcessAjaxResult(data, textStatus,
                    function (data, textStatus) {
                        _handlerMsg(data);
                    },
                    function (err, textStatus) {
                        alert('操作失败');
                    },
                    this);
            }
        });
    }

    this.UserRightsMgr = {
        init:
        function () {
            if (!!_inited) return;
            _init();
            _inited = true;
        }
    }
})();
$(function () {
    UserRightsMgr.init();
});